package cn.shengchao.examstarvideo.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
/**
 * @program: examstar-video
 * @description: 赶考视频获取
 * @author: Xiong weiqiang
 * @create: 2025-07-04 10:43
 */
public class GanKaoHttpUtil {
    private static final String serverUrl="https://www.gankao.com/api/service";
    private static final String appId="yunshi";
    private static final String appSecret="e4cd808c-4a79-11f0-bca4-b8599fe54952";
    public static final String URI_GET_PLAY_VIDEO_RESOURCE_FOR_WEB_API ="/getPlayVideoResourceForWeb";
    public static final String URI_CREATE_USER_API="/createUser";

    /**
     * 创建用户（有没有都访问一下）
     * @param uid
     * @return
     */
    public static boolean requestUserCreate(String uid){
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("app_id", appId);
        params.put("timestamp",System.currentTimeMillis());
        String token=getSecretTokenByParams(params,appSecret);
        params.put("token",token);
        String paramsStr= HttpUtil.toParams(params);

        String url = serverUrl +URI_CREATE_USER_API;

        String requestUrl = url+ "?"+paramsStr;

        System.out.println("赶考网创建用户请求："+requestUrl);
        HttpRequest request = HttpUtil.createGet(requestUrl);
        String result = request.execute().body();

        System.out.println("赶考网创建用户返回："+result);
        if (result != null && JSONUtil.isTypeJSON(result)) {
            int code=new JSONObject(result).getInt("code");
            if ( code== 10000||code==10002) {
                return true;
            }
        }
        return false;
    }
    /**
     * 获取赶考网播放地址（）
     * @param uid
     * @param courseId
     * @param sectionId
     * @return
     */
    public static String requestGetPlayVideoResourceForWeb(String uid, int courseId, int sectionId) {
        boolean isCreateUser=requestUserCreate(uid);
        if (!isCreateUser){return null;}
        Map<String, Object> params = new HashMap<>();
        params.put("uid", uid);
        params.put("course_id", courseId);
        params.put("section_id", sectionId);
        params.put("app_id", appId);
        params.put("timestamp",System.currentTimeMillis());
        String token=getSecretTokenByParams(params,appSecret);
        params.put("token",token);
        String paramsStr= HttpUtil.toParams(params);
        String url = serverUrl +URI_GET_PLAY_VIDEO_RESOURCE_FOR_WEB_API;

        String requestUrl = url+ "?"+paramsStr;

        System.out.println("赶考网视频请求："+requestUrl);
        HttpRequest request = HttpUtil.createGet(requestUrl);
        String result = request.execute().body();

        System.out.println("赶考网视频返回："+result);
        if (result != null && JSONUtil.isTypeJSON(result)){
            JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.getInt("code") == 10000) {
                String high= jsonObject.getJSONObject("data").getJSONObject("videoUrl").getStr("high");
                String normal= jsonObject.getJSONObject("data").getJSONObject("videoUrl").getStr("normal");
                return StrUtil.blankToDefault(high,normal);
            }
        }
        return null;
    }

    public static String getSecretTokenByParams(Map<String,Object> params, String secret) {
        StringBuilder paramsValue=new StringBuilder();
        if (params != null &&!params.isEmpty()) {
            List<String> keys = new ArrayList(params.keySet());
            List<String> sortKeys= CollUtil.sort(keys, String::compareTo);
            for (String key : sortKeys) {
                paramsValue.append(params.getOrDefault(key,"").toString());
            }
            paramsValue.append(secret);
            return DigestUtil.md5Hex(paramsValue.toString());
        }
        return null;
    }
}